package com.zhf.cloud.gateway.springcloudgateway.utils;

import com.zhf.cloud.gateway.springcloudgateway.entity.UserInfo;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author: 曾鸿发
 * @create: 2021-11-19 13:13
 * @description：获取登录用户信息
 **/
@Component
public class AppUserUtil {

    /**
     * 获取登陆的 LoginAppUser
     *
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static UserInfo getLoginAppUser() {
        OAuth2Authentication authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
        Authentication authenticationToken = authentication.getUserAuthentication();
        Map map = (Map) ((Map) authenticationToken.getDetails()).get("principal");

        int userId = (int) map.get("id");
        String username = map.get("username").toString();
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setUsername(username);
        return userInfo;
    }
}
